<?php

namespace App\Http\Service;

use App\Http\Repository\CaptchaRepository;

class CaptchaService extends BaseService
{
    protected $rep;
    protected $redisImageCaptchaKeyFormat = 'captcha:image:user:%s:token:%s';
    protected $redisMobileCaptchaKeyFormat = 'captcha:mobile:%s:user:%s:token:%s';
    protected $redisKeyExpiredTime = 300;

    public function __construct(CaptchaRepository $repository)
    {
        $this->rep = $repository;
    }

    public function setImageCaptcha($code, $user, $token)
    {
        $redisTokenKey = $this->getRedisImageCaptchaKey($user->id, $token);
        $redis = getRedis($user->id);
        $redis->set($redisTokenKey, $code);
        $redis->expire($redisTokenKey, $this->redisKeyExpiredTime);
    }

    public function checkImageCaptcha($code, $user, $token)
    {
        $redis = getRedis($user->id);
        $redisTokenKey = $this->getRedisImageCaptchaKey($user->id, $token);

        $captcha = $redis->get($redisTokenKey);

        if ($captcha != $code)
            return false;

        // 一次性失效
        $redis->del($redisTokenKey);

        return true;
    }

    public function setMobileCaptcha($code, $user, $token, $mobile)
    {
        $redisTokenKey = $this->getRedisMobileCaptchaKey($user->id, $token, $mobile);
        $redis = getRedis($user->id);
        $redis->set($redisTokenKey, $code);
        $redis->expire($redisTokenKey, $this->redisKeyExpiredTime);
    }

    public function checkMobileCaptcha($code, $user, $token, $mobile)
    {
        $redis = getRedis($user->id);
        $redisTokenKey = $this->getRedisMobileCaptchaKey($user->id, $token, $mobile);
        $captcha = $redis->get($redisTokenKey);

        if ($captcha != $code)
            return false;

        // 一次性失效
        $redis->del($redisTokenKey);

        return true;
    }

    private function getRedisImageCaptchaKey($userId, $token)
    {
        return sprintf($this->redisImageCaptchaKeyFormat, $userId, $token);
    }

    private function getRedisMobileCaptchaKey($userId, $token, $mobile)
    {
        return sprintf($this->redisMobileCaptchaKeyFormat, $mobile, $userId, $token);
    }

}
